package com.se.web;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.se.data.CapturedRequest;
import com.se.data.CapturedRequestService;
import com.se.data.CapturedRequestServiceDatastoreImpl;
import com.se.data.RequestKey;

@SuppressWarnings("serial")
public class RequestDetailServlet extends HttpServlet {

	private CapturedRequestService capturedRequestService = new CapturedRequestServiceDatastoreImpl();
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		long requestId = Long.parseLong(request.getParameter("id"));
		String tag = request.getParameter("tag");
		RequestKey key = getRequestKey(requestId, tag);
		CapturedRequest capturedRequest = capturedRequestService.getByKey(key);
		if (capturedRequest == null) {
			throw new ServletException("Request not found: " + key);
		}
		response.setContentType("text/plain");
		response.getWriter().write(capturedRequest.getContent());
	}

	private RequestKey getRequestKey(long requestId, String tag) {
		if ((tag == null) || (tag.length() == 0)) {
			return new RequestKey(requestId);
		}
		return new RequestKey(requestId, tag);
	}	
}
